<template>
	<view class="login">
		<view class="title">
			<view class="login-close" @click="goBack">
				<uni-icons type="back" size="30"></uni-icons>
			</view>	
		</view>
		<view class="title-text">
			<p>登录</p>
		</view>
		<view class="login-content" @click="showUser = false">
			<view class="dropdown" style="position:absolute;top:155rpx;left:90rpx;z-index: 10000;"
				v-if="showUser && JSON.parse(JSON.stringify(users)).length > 0">	          
				<view class="dropdown-item" hover-class="active-item" v-for="(item,index) in users" :key="index">
					<u-icon name="lock-open" style="color: #FFF" size="36rpx" @click="chooseUser(item)"></u-icon>
					<view class="u-m-l-20">
						<u-input v-model="item.username" type="text" height="30" :disabled="true"
							@click="chooseUser(item)" :custom-style="{'color': '#f1f1f1'}"></u-input>
						<u-input v-model="item.password" type="password" height="30" :disabled="true"
							:password-icon="false" @click="chooseUser(item)"
							:custom-style="{'color': '#f1f1f1','margin-left': '-10rpx'}"></u-input>
					</view>
				</view>
			</view>
			<view class="login-form">
				<u-form class="login-form_content" :model="form" ref="form" :error-type="['toast']">
					<u-form-item class="login-form_item" prop="login_id" left-icon="email" :left-icon-style="iconStyle">
						<u-input v-model="form.login_id" :placeholder="$t('mine.input_email')"
							@focus="showUser = true" />
					</u-form-item>
					<u-form-item class="login-form_item" prop="password" left-icon="lock" :left-icon-style="iconStyle">
						<u-input v-model="form.password" type="password" :placeholder="$t('mine.input_pwd')" />
					</u-form-item>
				</u-form>
			</view>
			<view class="login-button" @click="submit">
					<p class="login-button_p">登录</p>
			</view>
			<view class="link"  @click="$goPage('/forget_password', {}, true)">
				忘记密码
			</view>
		</view>
		<u-popup  v-model="show" mode="center" height="373rpx" width="624rpx">
			<view class="popup-top">
				<view class = "popup-top_icon">
						<u-icon name="info-circle" style="margin: 0 auto;" height="66rpx" width="66rpx"  size="66rpx"></u-icon>
				</view>
				<p class="popup-top_p">账号或密码错误，请确认后重新输入</p>
			</view>
			<view class="popup-buttom" @click="show=false">
				确定
			</view>
		</u-popup>
	</view>
</template>

<script>
	// import pageMixin from '@/utils/pageMixin';
	import {
		Base64
	} from 'js-base64';
	import {
		db
	} from '@/utils/sqlite';
	import sqliteSQL from "@/utils/sqliteSQL";
	import store from '@/store/index.js';
	import i18n from '../../lang/index'

	export default {
		// mixins: [pageMixin],
		data() {
			return {
				show: false,
				form: {
					email: '',
					password: ''
				},
				iconStyle: {
					fontSize: '36rpx',
					color: '#000000',
					display: 'flex',
					marginLeft: '15rpx',
				},
				rules: {
					login_id: [{
						required: true,
						message: this.$t('mine.msg_email'),
					}],
					password: [{
						min: 6,
						max: 18,
						message: this.$t('mine.msg_pwd'),
					}]
				},
				users: [],
				isRemember: false,
				showUser: false,
				userID: '',
				userSig: '',
				passwordIcon:true
			}
		},

		onLoad() {
			// .uni.removeStorageSync('user')
			i18n.global.locale = 'English'
			this.getStorage()

		},
		onShow() {
			i18n.global.locale = 'English'
			this.getStorage()
		},
		onReady() {
			// this.$refs.form.setRules(this.rules);
		},
		components: {},
		computed: {

		},
		methods: {
			goBack() {
				let pages = getCurrentPages();
				if (pages.length > 1) {
					this.$u.route({
						type: 'back',
						delta: 1
					})
				} else {
					this.$u.route({
						type: 'tab',
						url: '/pages/home/index'
					})
				}
			},
			chooseUser(item) {
				console.log(item)
				this.form.login_id = item.username;
				this.form.password = Base64.decode(item.password);
				console.log(this.form)
				this.showUser = false
			},
			getStorage() {
				// 判断本地存储中是否已经存过账号密码,如果有,则直接拿过来用
				if (uni.getStorageSync('user')) {
					let data = uni.getStorageSync('user')
					this.users = data
					console.log(data)
				}
			},
			setStorage() {
				if (uni.getStorageSync('user')) {
					var data = uni.getStorageSync('user')
					var flag = true
					data.forEach(item => {
						if (item.username == this.form.login_id) {
							flag = false
							item.password = this.form.password
						}
					})
					if (flag) {
						var newdata = {
							username: this.form.login_id,
							password: Base64.encode(this.form.password)
						}
						data.push(newdata)
						uni.setStorageSync('user', data)
					}

				} else {

					var data = []
					data.push({
						username: this.form.login_id,
						password: Base64.encode(this.form.password)
					})
					uni.setStorageSync('user', data)
				}
			},
			goSignIn() {
				let pages = getCurrentPages();
				if (pages.length > 1 && pages[pages.length - 2].route == 'pages/sign-in/index') {
					this.goBack();
				} else {
					this.$goPage('/sign-in', {}, true);
				}
			},
			submit() {
				let that = this;
				this.show =true
				this.$refs.form.validate(valid => {
					if (valid) {
						let data = {
							LoginId: this.form.login_id,
							Password: this.form.password
						};

						this.$http.post('/login/auth/account/login', data, store.state.jHeader).then(res => {
							console.log("aaaaaaaaa",res)
							this.userID = res.uid.toString()
							uni.setStorageSync('userInfo', res)

							//登录TIM
							const config = {
								userID: this.userID, //User ID
								SDKAppID: 1400533671, // Your SDKAppID
								secretKey: "aa636889f03251263f4820ab943441f10e056b7d85d23890b1f10beb09c6a00c", // Your secretKey
							};
							this.userSig = genTestUserSig(config).userSig;
							// this.bindTIMEvent()
							// this.loginTIM()

							uni.showToast({
								icon: 'none',
								title: this.$t('mine.login_success'),
							});
							if (res.lang == 1) {
								i18n.global.locale = '中文';
								uni.setStorageSync('lang', '中文');
							} else if (res.lang == 2) {
								i18n.global.locale = 'English';
								uni.setStorageSync('lang', 'English');
							} else if (res.lang == 3) {
								i18n.global.locale = 'русский';
								uni.setStorageSync('lang', 'русский');
							} else {
								this.changLang();
							}
							if (res.type == 1) {
								uni.setTabBarItem({
									index: 1,
									iconPath: '/static/images/tabbar/work.png',
									selectedIconPath: '/static/images/tabbar/work-fill.png',
									pagePath: '/pages/staff/bench/index'
								});
							} else {
								uni.setTabBarItem({
									index: 1,
									iconPath: '/static/images/tabbar/repair.png',
									selectedIconPath: '/static/images/tabbar/repair-fill.png',
									pagePath: '/pages/client/repair/index'
								})
							}
							
								// console.log('进入存储密码-----------------------------------------')
							this.setStorage()
							// console.log('出去存储密码------------------------------------------')
							//存入全局变量
							store.commit('$uStore', {
								name: 'vuex_user',
								value: res
							});
							uni.setStorageSync('userInfo', res);
							// uni.$u.route({
							// 	type: 'reLaunch',
							// 	url: '/pages/home/index'
							// });
						});
					} else {
						this.show =false
					}
				});
			},
			loginTIM() {
				let userSig = this.userSig;
				// login TUIKit
				uni.$TUIKit.login({
					userID: this.userID,
					userSig
				}).then((res) => {
					// sdk 初始化，当 sdk 处于ready 状态，才可以使用API，文档
					uni.showLoading({
						title: "初始化...",
					});
				});

			},
			bindTIMEvent() {
				uni.$TUIKit.on(uni.$TIM.EVENT.SDK_READY, this.handleSDKReady);
				uni.$TUIKit.on(uni.$TIM.EVENT.SDK_NOT_READY, this.handleSDKNotReady);
				uni.$TUIKit.on(uni.$TIM.EVENT.KICKED_OUT, this.handleKickedOut);
			},
			// sdk ready 以后可调用 API
			handleSDKReady(event) {
				uni.$chat_isSDKReady = true
				uni.setStorageSync('$chat_SDKReady', true);
				uni.hideLoading();

				// TUICallKit loginss
				uni.$TUICallKit.login({
					SDKAppID: 1400533671, // 开通实时音视频服务创建应用后分配的 SDKAppID
					userID: this.userID, // 用户 ID，可以由您的帐号系统指定
					userSig: this.userSig, // 身份签名，相当于登录密码的作用
				}, (res) => {
					if (res.code === 0) {
						uni.$TUICallKit.enableFloatWindow(true); // 开启小浮窗
					} else {
            uni.showToast({
              title: `login failed, error message = ${res.msg}`,
              duration: 2000
            });
					}
				});
			},
			handleSDKNotReady(event) {
			},

			handleKickedOut(event) {
				uni.clearStorageSync();
				uni.showToast({
					title: `${this.kickedOutReason(event.data.type)}被踢出，请重新登录。`,
					icon: "none",
				});
			},
			kickedOutReason(type) {
				switch (type) {
					case uni.$TIM.TYPES.KICKED_OUT_MULT_ACCOUNT:
						return "由于多实例登录";
					case uni.$TIM.TYPES.KICKED_OUT_MULT_DEVICE:
						return "由于多设备登录";
					case uni.$TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED:
						return "由于 userSig 过期";
					case uni.$TIM.TYPES.KICKED_OUT_REST_API:
						return "由于 REST API kick 接口踢出";
					default:
						return "";
				}
			},
			changLang() {
				let language = uni.getSystemInfoSync().language || '';
				let lang = language.split('-')[0] || '';
				if (lang == 'zh') {
					i18n.global.locale = '中文';
					console.log(i18n.global.locale);
					uni.setStorageSync('lang', '中文');
				} else if (lang == 'ru') {
					i18n.global.locale = 'русский';
					console.log(i18n.global.locale);
					uni.setStorageSync('lang', 'русский');
				} else {
					i18n.global.locale = 'English';
					console.log(i18n.global.locale);
					uni.setStorageSync('lang', 'English');
				}
			},
			// renderConversations(content, uid) {
			// 	let dbname = sqliteSQL.db.dbName
			// 	let path = '_doc/' + uid + '.db'
			// 	let insertData = []
			// 	let conversations = content.conversations
			// 	let sqlStr =
			// 		`REPLACE INTO im_conversation(conversation_id,conversation_name,conversation_avatar,conversation_type,
			// 	is_at_all,is_top,unread,last_message_id,last_message_group_id,last_message_type,last_message_timestamp,last_message_status,
			// 	last_message_sender_id,last_message_sender_name,last_message_recalled,last_message_read,last_message_text,last_message_content_type,
			// 	last_message_height,last_message_width,last_message_size,last_message_name,last_message_duration,last_message_url) values `

			// 	conversations.forEach(item => {

			// 		console.log("获取消息来了content", item)
			// 		let groupId = parseInt(item.groupId) || 0;
			// 		let groupAvatar = item.data.avatar || '';
			// 		let text = item.lastMessage.payload.text || '';
			// 		let senderData = item.lastMessage.senderData || {};
			// 		let isAtAll = false;
			// 		if (text.indexOf('【群公告】') !== -1) {
			// 			text = text.replace('【群公告】', '');
			// 			item.lastMessage.payload.text = text;
			// 			isAtAll = true;
			// 		}
			// 		let conversation_id = item.userId || ''
			// 		if (conversation_id == '' && item.groupId != '') {
			// 			conversation_id = item.groupId
			// 		}

			// 		console.log("item.data.name", item.data.name)
			// 		this.updateGroupUserInfo(groupId, item.lastMessage.senderId || '')

			// 		let data = {
			// 			'conversation_id': conversation_id,
			// 			'conversation_name': item.data.name,
			// 			'conversation_avatar': groupAvatar,
			// 			'conversation_type': item.type,
			// 			'is_at_all': item.isAtAll ? 1 : 0,
			// 			'is_top': item.top ? 1 : 0,
			// 			'unread': item.unread,
			// 			'last_message_id': item.lastMessage.messageId,
			// 			'last_message_group_id': item.lastMessage.groupId || '',
			// 			'last_message_type': item.lastMessage.type,
			// 			'last_message_timestamp': item.lastMessage.timestamp,
			// 			'last_message_status': item.lastMessage.status,
			// 			'last_message_sender_id': item.lastMessage.senderId || '',
			// 			'last_message_sender_name': senderData.name || '',
			// 			'last_message_recalled': item.lastMessage.recalled ? 1 : 0,
			// 			'last_message_read': item.lastMessage.read ? 1 : 0,
			// 			'last_message_text': item.lastMessage.payload.text || '',
			// 			'last_message_content_type': item.lastMessage.payload.contentType || '',
			// 			'last_message_height': item.lastMessage.payload.height || '',
			// 			'last_message_width': item.lastMessage.payload.width || '',
			// 			'last_message_size': item.lastMessage.payload.size || '',
			// 			'last_message_name': item.lastMessage.payload.name || '',
			// 			'last_message_duration': item.lastMessage.payload.duration || '',
			// 			'last_message_url': item.lastMessage.payload.url || '',
			// 		};
			// 		let keys = Object.keys(data)
			// 		let keyStr = keys.toString()
			// 		let valStr = ''
			// 		for (let key in data) {
			// 			valStr += ('"' + data[key] + '",')
			// 		}
			// 		valStr = valStr.substr(0, valStr.length - 1);
			// 		sqlStr += `(${valStr}),`
			// 	})
			// 	sqlStr = sqlStr.substr(0, sqlStr.length - 1);
			// 	sqlStr += ';'

			// 	console.log("uid", uid)
			// 	if (uid > 0) {

			// 		let dbname = sqliteSQL.db.dbName
			// 		let path = '_doc/' + uid + '.db'

			// 		//打开数据库
			// 		let isOpen = db.isOpenDB(dbname, path)
			// 		if (isOpen) {

			// 			console.log("insertData", sqlStr)

			// 			// plus.sqlite.executeSql({
			// 			// 	name: dbname,
			// 			// 	sql: sqlStr,
			// 			// 	success: (e) => {
			// 			// 		console.log("新增成功了哈", e);
			// 			// 	},
			// 			// 	fail: (e) => {
			// 			// 		console.log("新增失败了", e);
			// 			// 	}
			// 			// })
			// 		} else {
			// 			plus.sqlite.openDatabase({
			// 				name: dbname,
			// 				path: path,
			// 				success: function(res) {
			// 					plus.sqlite.executeSql({
			// 						name: dbname,
			// 						sql: sqlStr,
			// 						success: (e) => {
			// 							console.log("新增成功了哈", e);
			// 						},
			// 						fail: (e) => {
			// 							console.log("新增失败了", e);
			// 						}
			// 					})
			// 				},
			// 				fail: function(e) {
			// 					console.log('failed: ' + JSON.stringify(e))
			// 				}
			// 			});
			// 		}
			// 	}

			// 	let unreadTotal = content.unreadTotal;
			// 	this.setUnreadAmount(unreadTotal, uid);
			// 	this.saveConversationAvatar(uid);
			// },
			setUnreadAmount(unreadTotal, uid) {

				//获取消息通知数量
				uni.request({
					url: "https://tapi.i-dock.net/msg/system/type/count?uid=" + uid,
					method: "GET",
					success: (res) => {
						let code = res.data.code || 0
						if (code == 200) {
							let data = res.data.data || 0
							unreadTotal += data.totalCount
							console.log("unreadTotal", unreadTotal)
							uni.setStorageSync('systemNotifyMsgUnread', unreadTotal)
							if (unreadTotal > 0) {
								if (unreadTotal > 99) {
									unreadTotal = '99+'
								}
								////plus.runtime.setBadgeNumber(unreadTotal)
							} else {
								////plus.runtime.setBadgeNumber(0)
							}
							if (data.count2 > 0) {
								uni.setTabBarBadge({
									index: 2,
									text: data.count2.toString()
								});
							} else {
								uni.removeTabBarBadge({
									index: 2
								});
							}
						}
					}
				})
			},
			// saveConversationAvatar(uid) {
			// 	let dbname = sqliteSQL.db.dbName
			// 	let path = '_doc/' + uid + '.db'

			// 	let selectSql = 'SELECT * FROM im_conversation ORDER BY last_message_timestamp DESC'
			// 	let isOpen = db.isOpenDB(dbname, path)
			// 	if (isOpen) {

			// 		plus.sqlite.selectSql({
			// 			name: dbname,
			// 			sql: selectSql,
			// 			success: (result) => {
			// 				//保存会话列表头像
			// 				for (let i = 0; i < result.length; i++) {
			// 					let groupId = parseInt(result[i].conversation_id) || 0
			// 					let groupAvatar = result[i].conversation_avatar || ''
			// 					let conversation_id = result[i].conversation_id || ''

			// 					if (groupAvatar != '' && groupAvatar.indexOf('http') == 0) {
			// 						uni.downloadFile({
			// 							url: groupAvatar,
			// 							success: (res) => {
			// 								if (res.statusCode === 200) {
			// 									uni.saveFile({
			// 										tempFilePath: res.tempFilePath,
			// 										success: function(result) {

			// 											let updateSql =
			// 												`UPDATE im_conversation SET conversation_avatar="${result.savedFilePath}" WHERE conversation_id="${conversation_id}"`
			// 											plus.sqlite.executeSql({
			// 												name: sqliteSQL.db
			// 													.dbName,
			// 												sql: updateSql,
			// 												success: (e) => {
			// 													console
			// 														.log(
			// 															"后面修改成功了哈"
			// 														)
			// 												},
			// 												fail: (e) => {
			// 													console
			// 														.log(
			// 															"后面修改失败了哈"
			// 														)
			// 												}
			// 											})
			// 										}
			// 									})
			// 								}
			// 							}
			// 						})
			// 					}
			// 				}
			// 			},
			// 			fail: (e) => {
			// 				console.log("新增失败了", e);
			// 			}
			// 		})
			// 	}
			// },
			subscribeGroup(uid) {
				if (uid > 0) {
					console.log("用户 ID 啊", uid)
					uni.request({
						// url: "https://tapi.i-dock.net/mgr/user/group/get?uid=" + uid,
						url: "http://127.0.0.1:8001/mgr/user/group/get?uid=" + uid,
						method: "GET",
						success: (res) => {
							console.log("请求成功拉", res)
							let code = res.data.code || 0
							if (code == 200) {
								let group = res.data.data || []
								if (group.length > 0) {
									this.goEasy.im.subscribeGroup({
										groupIds: group,
										onSuccess: function() {
											console.log('订阅群消息成功');
										},
										onFailed: function(error) {
											console.log('订阅群消息失败:', error);
										}
									});
								}
							}
						}
					})
				}
			},
			// updateGroupUserInfo(gid, userId) {
			// 	console.log("gid", gid)
			// 	console.log("userId", userId)
			// 	if (gid > 0) {
			// 		uni.request({
			// 			url: "https://tapi.i-dock.net/mgr/user/group/member/list/data?gid=" + gid,
			// 			method: "GET",
			// 			success: (res) => {
			// 				console.log("res", res)
			// 				if (res.data.code == 200) {
			// 					let data = res.data.data || []
			// 					let groupMemberList = data.groupMemberList || []
			// 					for (var i in groupMemberList) {

			// 						if (groupMemberList[i].UserId == userId) {
			// 							uni.setStorageSync('groupMemberUserName-' + userId, groupMemberList[i]
			// 								.UserName)
			// 							let updateSql =
			// 								`UPDATE im_conversation SET last_message_sender_name="${groupMemberList[i].UserName}" WHERE conversation_id="${gid}"`
			// 							plus.sqlite.executeSql({
			// 								name: sqliteSQL.db
			// 									.dbName,
			// 								sql: updateSql,
			// 								success: (e) => {
			// 									console.log(
			// 										"发送人修改成功了哈", updateSql)
			// 								},
			// 								fail: (e) => {
			// 									console.log(
			// 										"发送人后面修改失败了哈"
			// 									)
			// 								}
			// 							})
			// 						}
			// 					}
			// 				}
			// 				console.log("请求群信息成功：" + gid + "-" + userId, res)
			// 			}
			// 		})
			// 	}
			// }
		}
	}
</script>

<style lang="scss" scoped>
	.login{
		background-color: #FEFEFE;
		height: 1624rpx;
		width: 100%;
		border-top: 1rpx solid #fff;
	}
	.title{
		display: flex;
		text-align: center;
		vertical-align: middle;
		width: 100%;
		height: 88rpx;
		margin-top: 88rpx;
		.login-close {
			width: 48rpx;
			height: 48rpx;
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			// margin-top: 110rpx;
			margin-left: 48rpx;
			.icon {
				font-size: 42rpx;
				color: #000000;
			}
		}
	}
	.title-text{
		width: 100%;
		height: 120rpx;
		line-height: 120rpx;
		margin-top: 120rpx;
		p{	
			margin:0 auto;
			width: 128rpx;
			height: 90rpx;
			font-size: 64rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #000000;
			-webkit-background-clip: text;
		}
	}
	.login-bg {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;

		.login-bg_img {
			width: 100%;
			height: 100%;
			// padding-bottom: constant(safe-area-inset-bottom);
			// padding-bottom: env(safe-area-inset-bottom);  
		}
	}


	.login-title {
		font-size: 48rpx;
		font-family: 'Source Han Sans CN';
		font-weight: bold;
		color: #ffffff;
		padding: 0 48rpx;
		position: absolute;
		top: 220rpx;
		left: 0;
	}

	.login-content {
		position: absolute;
		left: 50%;
		top: 380rpx;
		margin-top: 80rpx;
		transform: translateX(-50%);
	}

	.dropdown {
		background-color: #303030;
		width: 490rpx;
		border-radius: 10rpx;
		padding: 20rpx 0;

		.dropdown-item {
			display: flex;
			align-items: center;
			padding: 20rpx 30rpx;
		}

		.active-item {
			background-color: #4c4d4e;
			opacity: 0.6;
			cursor: pointer;
		}
	}

	.login-form {
		border-radius: 20rpx;
		background-color: #ffffff;
		margin: 0 auto;
		padding: 38rpx;

		&_content {
			padding: 24rpx 0;
		}

		&_item {
			margin: 0 auto;
			padding: 22rpx 24rpx;
			width: 622rpx;
			height: 112rpx;
			margin-top: 10rpx;
			border-radius: 10rpx;
			background: #000000;
			background-color: rgba(0, 0, 0, 0.03);
		}
	}

	.login-button {
		display: flex;
		width: 622rpx;
		height: 96rpx;
		background: #476BEE;
		border-radius: 24rpx 24rpx 24rpx 24rpx;
		opacity: 0.5;
		align-items: center;
		text-align: center;
		vertical-align: middle;
		margin: 0 auto;
		&_p{
			margin: 0 auto;
			height: 40rpx;
			font-size: 32rpx;
			font-family: PingFang SC-Semibold, PingFang SC;
			font-weight: 600;
			color: #FEFEFE;
		}
	}
	.link{
		margin: 32rpx auto;
		width: 128rpx;
		height: 40rpx;
		font-size: 32rpx;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		color: #476BEE;
		line-height: 40rpx;
		-webkit-background-clip: text;
	}
	.popup-top{
		width: 100%;
		height: 181rpx;
		&_icon{
			margin: 0 auto;
			width: 100%;
			height: 136rpx;
			display: flex;
			u-icon{
				margin: 0 auto;
			}
		}
		&_p{
			width: 512rpx;
			height: 45rpx;
			font-size: 32rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #000000;
			line-height: 38rpx;
			margin: 0 auto;
			-webkit-background-clip: text;
		}
	}
	.popup-buttom{
		margin: 48rpx auto;
		width: 496rpx;
		height: 96rpx;
		background: #476BEE;
		opacity: 1;
		border-radius: 25rpx;
		line-height: 96rpx;
		text-align: center;
		vertical-align: middle;
		color: #fff;
	}
	.login-tips {
		font-size: 28rpx;

		&_left {
			color: #999999;

			&--text {
				color: $u-type-primary;
				text-decoration: underline;
			}
		}
	}
</style>
